package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Visitor;
import cn.wolfcode.wolf2w.repository.VisitorRepository;
import cn.wolfcode.wolf2w.service.IVisitorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;

/**
 * 横幅服务接口实现
 */
@Service

public class VisitorServiceImpl implements IVisitorService {

    @Autowired
    private VisitorRepository visitorRepository;

    @Override
    public void save(Visitor visitor) {
        visitorRepository.save(visitor);
    }

    @Override
    public void update(Visitor visitor) {
        visitorRepository.save(visitor);
    }

    @Override
    public Visitor get(String id) {
        return visitorRepository.findById(id).orElse(null);
    }

    @Override
    public List<Visitor> list() {
        return visitorRepository.findAll();
    }

    @Override
    public void saveOrUpdate(Visitor visitor) {

    }

    @Override
    public void delete(String id) {
        visitorRepository.deleteById(id);
    }

    @Override
    public Visitor getByOwnerId(String ownerId, String uid) {
        Visitor visitor =null;
        if (StringUtils.hasLength(ownerId)) {
             visitor = visitorRepository.findByOwnerId(ownerId);
        }
        if (visitor == null) {
            this.save(visitor);
        }
        List<String> uids = visitor.getVistors();
        if (!uids.contains(uid)) {
            uids.add(0, uid);
        } else {
            uids.remove(uid);
            uids.add(0, uid);
        }
        visitor.setVistors(uids);
        visitor.setTotalCount(visitor.getTotalCount() + 1);
        this.update(visitor);
        return visitor;
    }

    @Override
    public Visitor queryByOwnerId(String ownerId, String id) {

        return visitorRepository.findByOwnerId(ownerId);
    }
}
